package JZOffer;

/**
 * @author Lw中
 * @date 2021/7/11 16:58
 */
public class Jz24 {

    /**
     *  反转链表
     */

    /**
     * 初始化单链表
     */
    public class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
    }

    public ListNode reverseList(ListNode head) {
        /*ListNode pre = head;
        ListNode temp = null;
        while(head.next!= null) {
            temp = head.next;
            ListNode last = temp.next;

            temp.next = pre;
            pre = pre.next;
            head = pre;

            temp = last;
        }*/

        // 当前节点
        ListNode cur = head;
        // 当前节点的前置节点
        ListNode pre = null;
        // 循环链表中的每个节点，将cur节点的后继指向pre
        while (head != null) {
            head = cur.next;
            cur.next = pre;
            pre = cur;
            cur = head;
        }

        return pre;

//        ListNode cur = head;
//        ListNode pre = null;
//        while (cur != null) {
//            ListNode nxt = cur.next;
//            cur.next = pre;
//            pre = cur;
//            cur = nxt;
//        }
//        return pre;
    }

}
